package com.cz.run.bumng;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cz.run.beans.mysql.*;
import com.cz.run.bumng.model.PageModel;
import com.cz.run.bumng.model.Result;
import com.cz.run.bumng.model.TaskMdoel;
import com.cz.run.service.*;
import com.cz.run.utils.FileUtil;
import com.cz.run.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by deior on 2018/6/9.
 */
@Controller
@RequestMapping("/bumng")
public class TaskController {

    @Autowired
    private ITaskService iTaskService;
    @Autowired
    private IUserBaseService iUserBaseService;
    @Autowired
    private IAdvertisementService iAdvertisementService;

    @Autowired
    private IUserPointService iUserPointService;

    @Autowired
    private IAreaCodeService iAreaCodeService;

    @Value("${spring.html.path}")
    private String htmls;

    private static  final String url ="http://120.79.249.39:8092";


    @RequestMapping(value ="/taskList.htm",method = RequestMethod.GET)
    public String taskList(HttpServletRequest request, @ModelAttribute BumngUser bumngUser, Model model){

        BumngUser bumngUser1 = (BumngUser) request.getSession().getAttribute("bumngUser");

        if(null==bumngUser1){
            return "login";
        }
        model.addAttribute("bumngUser",bumngUser1);


        String phone = request.getParameter("phone");
        model.addAttribute("phone",phone);

        PageModel pageModel =  PageUtil.getPageData(request);

        EntityWrapper<Task> ew = new EntityWrapper<>();
        ew.where("1 = 1").and(StringUtils.hasLength(phone),"phone = {0}",phone)
                .orderBy("create_time desc limit "+pageModel.getPageNum()+","+pageModel.getPageSize());
        List<Task> tasks =  iTaskService.selectList(ew);



        List<TaskMdoel> taskMdoels = new ArrayList<>();

        BeanCopier bc = BeanCopier.create(Task.class,TaskMdoel.class,false);

        for(Task task:tasks) {
            TaskMdoel taskMdoel =new TaskMdoel();
            bc.copy(task,taskMdoel,null);

            EntityWrapper<UserBase> uew = new EntityWrapper<>();
            uew.where("id={0}",task.getUserId());
            UserBase userBase = iUserBaseService.selectOne(uew);

            EntityWrapper<UserBase> aew = new EntityWrapper<>();
            aew.where("id={0}",task.getAuditId());
            UserBase auserBase = iUserBaseService.selectOne(aew);



            taskMdoel.setUserName(null==userBase?"":userBase.getRealName());
            taskMdoel.setAuditName(null==userBase?"":auserBase.getRealName());
            taskMdoels.add(taskMdoel);
        }

        EntityWrapper<Task> ew1 = new EntityWrapper<>();
        ew1.where("1 = 1").and(StringUtils.hasLength(phone),"phone = {0}",phone)
               ;
        int count =  iTaskService.selectCount(ew1);

        model.addAttribute("pageTotal",count%pageModel.getPageSize()>0?count/10+1:count/10);
        model.addAttribute("pageNum",(pageModel.getPageNum())/10+1);

        model.addAttribute("tasks",taskMdoels);

        return "taskList";
    }

    @RequestMapping(value = "updateTaskStatus.do", method = RequestMethod.POST)
    @ResponseBody
    public Object updateTaskStatus(HttpServletRequest request,  Model model) {


        String id =request.getParameter("id");
        String status =request.getParameter("status");

        EntityWrapper<Task> ew = new EntityWrapper<>();
        ew.where("id = {0}",id);
        Task task =iTaskService.selectOne(ew);
        task.setAuditStatus(Integer.parseInt(status));
        iTaskService.update(task,ew);

        EntityWrapper<UserPoint> uew = new EntityWrapper<>();
        uew.where("user_id={0}",task.getUserId());
        UserPoint userPoint =iUserPointService.selectOne(uew);
        if("1".equals(status)){
            userPoint.setPointFrozen(userPoint.getPointFrozen()-task.getIntegral());

            EntityWrapper<UserPoint> uew1 = new EntityWrapper<>();
            uew1.where("user_id={0}",0);
            UserPoint usertPoint =iUserPointService.selectOne(uew1);

            usertPoint.setPoint(usertPoint.getPoint()+task.getIntegral());
        }else{
            userPoint.setPoint(userPoint.getPoint()+task.getIntegral());
            userPoint.setPointFrozen(userPoint.getPointFrozen()-task.getIntegral());
        }
        iUserPointService.updateById(userPoint);

        return  new Result(true,"成功");
    }

    @RequestMapping(value = "editTask.htm")
    public String editTask(HttpServletRequest request, Model model) {
        BumngUser bumngUser1 = (BumngUser) request.getSession().getAttribute("bumngUser");

        if(null==bumngUser1){
            return "login";
        }
        model.addAttribute("bumngUser",bumngUser1);
        String id =request.getParameter("id");

            EntityWrapper<Task> ew = new EntityWrapper<>();
            ew.where("id = {0}",id);
          Task task =  iTaskService.selectOne(ew);

          EntityWrapper<Advertisement> adew = new EntityWrapper<>();
          adew.where("task_id={0}",id);
          Advertisement advertisement =iAdvertisementService.selectOne(adew);

        BeanCopier bc = BeanCopier.create(Task.class,TaskMdoel.class,false);
        TaskMdoel taskMdoel =new TaskMdoel();
        bc.copy(task,taskMdoel,null);

        EntityWrapper<UserBase> uew = new EntityWrapper<>();
        uew.where("id={0}",task.getUserId());
        UserBase userBase = iUserBaseService.selectOne(uew);

        taskMdoel.setCode(null==taskMdoel.getCode()?"普通":"86".equals(taskMdoel.getCode())?"全国":"普通");
        taskMdoel.setUserName(null==userBase?"":userBase.getRealName());
        taskMdoel.setPictureUrl(advertisement.getImage());
        taskMdoel.setSort(advertisement.getSort());
        model.addAttribute("task",taskMdoel);

        return "editTask";
    }

    @RequestMapping(value = "addTask.do", method = RequestMethod.POST)
    @ResponseBody
    public Object addTask(HttpServletRequest request, @ModelAttribute TaskMdoel task, Model model) {


        if(StringUtils.isEmpty(task.getSort())||StringUtils.isEmpty(task.getId())||StringUtils.isEmpty(task.getContent())||StringUtils.isEmpty(task.getPhone())||StringUtils.isEmpty(task.getContactName())||StringUtils.isEmpty(task.getPictureUrl()))
              {

            return  new Result(false,"参数不能为空");
        }


        BeanCopier bc = BeanCopier.create(TaskMdoel.class,Task.class,false);
        Task taskMdoel =new Task();
        bc.copy(task,taskMdoel,null);

        String html = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>"+"任务"+"</title>\n" +
                "</head>\n" +
                "<body>"+task .getUrl()+"</body>\n" +
                "\t</html>";
        taskMdoel.setHtml(taskMdoel.getUrl());
        String fileName = UUID.randomUUID().toString();
        try {
            FileUtil.saveFile(html.getBytes(),htmls,fileName+".html");
            String htmlUrl = url+"/html/"+fileName+".html";
            taskMdoel.setUrl(htmlUrl);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        taskMdoel.setUpdateTime(new Date());
        EntityWrapper<Task> ew = new EntityWrapper<>();
        ew.where("id = {0}",task.getId());
          iTaskService.updateById(taskMdoel);


        EntityWrapper<Task> ew1 = new EntityWrapper<>();
        ew1.where("id = {0}",task.getId());
        Task task1 =  iTaskService.selectOne(ew1);

        EntityWrapper<Advertisement> adew = new EntityWrapper<>();
        adew.where("task_id={0}",task.getId());
        Advertisement advertisement =iAdvertisementService.selectOne(adew);

        if(null==advertisement){
            advertisement =new Advertisement();
            advertisement.setImage(task.getPictureUrl());
            advertisement.setSort(task.getSort());
            advertisement.setTaskId(task.getId());
            advertisement.setType(null==task1.getCode()?1:"86".equals(task1.getCode())?2:1);
            iAdvertisementService.insert(advertisement);
        }else {
            advertisement.setImage(task.getPictureUrl());
            advertisement.setSort(task.getSort());
            advertisement.setTaskId(task.getId());
            advertisement.setType(null==task1.getCode()?1:"86".equals(task1.getCode())?2:1);
            iAdvertisementService.updateById(advertisement);
        }

        return  new Result(true,"成功");
    }

    @RequestMapping(value = "area.htm")
    public String area(HttpServletRequest request, Model model) {
        BumngUser bumngUser1 = (BumngUser) request.getSession().getAttribute("bumngUser");

        if(null==bumngUser1){
            return "login";
        }
        model.addAttribute("bumngUser",bumngUser1);
        String name =request.getParameter("name");
        PageModel pageModel =  PageUtil.getPageData(request);


        EntityWrapper<AreaCode> ew = new EntityWrapper<>();
        ew.where("1 = 1").and(StringUtils.hasLength(name),"name={0}",name)
                .orderBy("id limit "+pageModel.getPageNum()+","+pageModel.getPageSize());
        List<AreaCode> areaCodes =  iAreaCodeService.selectList(ew);

        model.addAttribute("areaCodes",areaCodes);
        model.addAttribute("name",name);


        EntityWrapper<AreaCode> ew1 = new EntityWrapper<>();
        ew1.where("1 = 1").and(StringUtils.hasLength(name),"name={0}",name);
        int count =  iAreaCodeService.selectCount(ew1);
        model.addAttribute("pageTotal",count%pageModel.getPageSize()>0?count/10+1:count/10);
        model.addAttribute("pageNum",(pageModel.getPageNum())/10+1);


        return "area";
    }


    @RequestMapping(value = "editArea.htm")
    public String editArea(HttpServletRequest request, Model model) {
        BumngUser bumngUser1 = (BumngUser) request.getSession().getAttribute("bumngUser");

        if(null==bumngUser1){
            return "login";
        }
        model.addAttribute("bumngUser",bumngUser1);
        String id =request.getParameter("id");

        EntityWrapper<AreaCode> ew = new EntityWrapper<>();
        ew.where("id = {0}",id);
        AreaCode areaCode =  iAreaCodeService.selectOne(ew);

        model.addAttribute("areaCode",areaCode);

        return "editArea";
    }

    @RequestMapping(value = "addArea.do", method = RequestMethod.POST)
    @ResponseBody
    public Object addArea(HttpServletRequest request, Model model) {


        String price = request.getParameter("price");
        String id = request.getParameter("id");
        if(StringUtils.isEmpty(price))
        {
            return  new Result(false,"参数不能为空");
        }

        AreaCode areaCode = new AreaCode();
        areaCode.setId(Long.parseLong(id));
        areaCode.setPrice(Double.parseDouble(price));

        iAreaCodeService.updateById(areaCode);

        return  new Result(true,"成功");
    }
    @RequestMapping(value = "json.do", method = RequestMethod.GET)
    @ResponseBody
    public void json(HttpServletRequest request,  Model model) {
        org.json.JSONArray jsonArray = new org.json.JSONArray("");

        for (int i = 0; i < jsonArray.length(); i++) {
            org.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
            org.json.JSONArray jsonArray1 =  (org.json.JSONArray)jsonObject.get("citys");
            for (int j = 0; j < jsonArray1.length(); j++) {
                org.json.JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
                AreaCode areaCode = new AreaCode();
                String code = (String) jsonObject2.get("city_key");
                String name =(String)jsonObject2.get("city_name");
                areaCode.setCode(code);
                    areaCode.setName(decodeUnicode(name));

                iAreaCodeService.insert(areaCode);
            }
        }
    }

    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }
}
